<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="分类名" prop="cName">
                <el-input v-model="queryParams.cName" placeholder="请输入物料分类姓名" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="父id" prop="pId">
                <el-input v-model="queryParams.pId" placeholder="请输入父id" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="逻辑删除" prop="isDeleted">
          <el-input
            v-model="queryParams.isDeleted"
            placeholder="请输入逻辑删除"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:category:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:category:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['system:category:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['system:category:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="物料分类id" align="center" prop="cId" />
            <el-table-column label="物料分类姓名" align="center" prop="cName" />
            <el-table-column label="父级id" align="center" prop="pId">
                <template slot-scope="scope">
                    <span v-if="scope.row.pId == 0 || scope.row.pId == null">--</span>
                    <span v-if="scope.row.pId != 0 && scope.row.pId != null">{{ scope.row.pId }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="逻辑删除" align="center" prop="isDeleted" /> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:category:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:category:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改物料分类对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="分类姓名" prop="cName">
                    <el-input v-model="form.cName" placeholder="请输入物料分类姓名" />
                </el-form-item>
                <el-form-item label="父级id" prop="pId">
                    <el-cascader :options="options" v-model="form.pId" :show-all-levels="false" placeholder="请选择父级id" :props="{ checkStrictly: true }" clearable></el-cascader>
                    <!-- <el-cascader :options="options" v-model="form.pId" :show-all-levels="false"
                        placeholder="请选择父级id"></el-cascader> -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, getLevel } from "@/api/system/category";

export default {
    name: "Category",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 物料分类表格数据
            categoryList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                cName: null,
                pId: null,
                isDeleted: null
            },
            options: [],//级联选项
            // 表单参数
            form: {},
            // 表单校验
            rules: {
            }
        };
    },
    created() {
        this.getList();
        getLevel().then(res => {
            this.removeEmptyChildren(res.data);
            res.data.push({ label: '无父级', value: 0 })
            this.options = res.data
        })
    },
    methods: {
        removeEmptyChildren(item, value) {
            item.forEach((item, index) => {
                // 如果没有子项，删除 children 属性  
                if (item.children && item.children.length === 0) {
                    delete item.children;
                } else if (item.children) {
                    // 如果有子项，递归调用  
                    this.removeEmptyChildren(item.children, value);
                    // 在这里找到值相等的项  
                    const targetIndex = item.children.findIndex(child => {
                        const isMatch = child.pId === value; // 检查 pId 是否与 value 匹配  
                        return isMatch; // 确保返回布尔值  
                    });
                    console.log(targetIndex, "sdfs是非得失");
                    if (targetIndex !== -1) {
                        // 找到匹配后，删除所有子项  
                        item.children = [];  // 这样可以清空全部子项  
                    }
                    // 最后检查子项，若没有子项则同样删除  
                    if (item.children && item.children.length === 0) {
                        delete item.children;
                    }
                }
            });
        },
        /** 查询物料分类列表 */
        getList() {
            this.loading = true;
            listCategory(this.queryParams).then(response => {
                this.categoryList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                cId: null,
                cName: null,
                pId: null,
                updateTime: null,
                isDeleted: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.cId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加物料分类";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const cId = row.cId || this.ids
            getCategory(cId).then(response => {
                this.form = response.data;
                this.form.pId = row.pId
                console.log(this.form,"上事实上事实上");
                
                this.removeEmptyChildren(this.options, this.form.pId)
                this.open = true;
                this.title = "修改物料分类";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.cId != null) {
                        console.log(this.form,"sfsf发生的事");

                        // this.form.pId = this.form.pId[this.form.pId.length - 1];

                        updateCategory(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        this.form.pId = this.form.pId[this.form.pId.length - 1];
                        addCategory(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const cIds = row.cId || this.ids;
            this.$modal.confirm('是否确认删除物料分类编号为"' + cIds + '"的数据项？').then(function () {
                return delCategory(cIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/category/export', {
                ...this.queryParams
            }, `category_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>